package com.zhangzhan.gulimallcart.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zhangzhan.gulimallcart.tos.TempOrInfoUserTo;
import com.zhangzhan.gulimallcommcon.tos.MemberTo;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;
import java.util.UUID;

import static com.zhangzhan.gulimallcommcon.constant.AuthConstant.SESSION_USER_INFO_KEY;
import static com.zhangzhan.gulimallcommcon.constant.CookieConstant.USER_KEY;
import static com.zhangzhan.gulimallcommcon.constant.CookieConstant.USER_KEY_TIMEOUT;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/6/29 4:01
 */
@Component
public class TempOrInfoUserInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<TempOrInfoUserTo> threadLocal = new ThreadLocal<>();

    /**
     * 请求之前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        TempOrInfoUserTo to = new TempOrInfoUserTo();

        //获取用户是否登录
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(SESSION_USER_INFO_KEY);
        if (!Objects.isNull(attribute)) {
            //登录了
            MemberTo memberTo = JSON.parseObject(JSON.toJSONString(attribute), MemberTo.class);
            to.setUserId(memberTo.getId());
        }

        //获取cookie中的临时用户标签
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (cookieName.equals(USER_KEY)) {
                    to.setUserKey(cookie.getValue());
                    to.setUserKeyCookie(true);
                }
            }
        }

        if (StrUtil.isBlank(to.getUserKey())) {
            to.setUserKey(UUID.randomUUID().toString());
        }

        //存入cookie
        threadLocal.set(to);

        return true;
    }

    /**
     * 请求过后拦截
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //在cookie中存入user_key
        TempOrInfoUserTo tempOrInfoUserTo = threadLocal.get();
        if (!tempOrInfoUserTo.getUserKeyCookie()) {
            Cookie cookie = new Cookie(USER_KEY, tempOrInfoUserTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(USER_KEY_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
